package com.wsh.lab.controller;

import com.wsh.lab.business.IHello;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author wsh
 * @date 2021-11-02 23:15
 */
@WebServlet("hello")
public class HelloServlet extends HttpServlet {
    private IHello hello;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 方式一：需要查看源码才能发现其属性名称
        //ApplicationContext ctx = (ApplicationContext) this.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        // 方式二：使用Spring内置工具获取
        ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());
        hello = ctx.getBean(IHello.class);
        String sayHello = hello.sayHello();
        System.err.println("sayHello:" + sayHello);
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("<h2>" + sayHello + "</h2>");
    }
}
